package com.scs.application.modules.msg.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.consts.GlobalConsts;
import com.scs.application.core.mvc.controller.CrudController;
import com.scs.application.core.query.QueryContext;
import com.scs.application.core.query.QueryContextHolder;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.core.utils.UserUtils;
import com.scs.application.core.utils.UtilCommon;
import com.scs.application.modules.base.util.CommonService;
import com.scs.application.modules.msg.entity.InnerInbox;
import com.scs.application.modules.msg.service.InnerInboxService;
import com.scs.application.modules.msg.vo.InnerInboxVO;
import com.scs.application.modules.sys.model.PageResult;
import com.scs.application.modules.sys.model.RestResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.util.Date;
import java.util.Map;


@RestController
@RequestMapping("/msg/inner_inbox")
public class InnerInboxController extends CrudController<InnerInboxService,InnerInbox> {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    /**
     * 获取数据列表
     */
    @Override
    public PageResult page() {
        QueryContext queryContext = QueryContextHolder.currentContext();
        QueryWrapper<InnerInboxVO> queryWrapper = queryContext.getWrapper();
        queryWrapper.eq("receiver_user_code", UserUtils.currentUser().getCode());

        IPage pageResult = service.page(queryContext);
        return PageResult.ok("get InnerInbox list success", pageResult.getRecords(), pageResult.getTotal());
    }

    /**
     * 根据ID查找数据
     */
    @GetMapping("/findInnerInboxById")
    public RestResult findInnerInboxById(@RequestParam("id") String id) {
        InnerInboxVO entity = service.findInnerInboxById(id);
        if (entity == null) {
            return RestResult.error("未找到符合条件的数据");
        }
        return RestResult.ok("获取数据成功", entity);
    }


    /**
     * 读取消息
     *
     * @param id
     * @return
     */
    @PutMapping("/{id}/read")
    public RestResult readMessage(@PathVariable("id") Serializable id) {
        boolean success = service.update(Wrappers.<InnerInbox>update()
                .set("is_read", GlobalConsts.YES_STR)
                .set("gmt_read", new Date())
                .eq("id", id)
        );
        return RestResult.ok("标记已读成功");
    }

    @PutMapping("/read_all")
    public RestResult readAllMessage() {
        boolean success = service.update(Wrappers.<InnerInbox>update()
                .set("is_read", GlobalConsts.YES_STR)
                .set("gmt_read", new Date())
                .eq("is_read", GlobalConsts.NO_STR)
                .eq("receiver_user_code", UserUtils.currentUser().getCode())
        );
        return RestResult.ok("标记已读成功");
    }

    /**
     * 获取当前用户未读消息
     *
     * @return
     */
    @GetMapping("/unread_count")
    public RestResult getUnreadCount() {
//        QueryWrapper<InnerInbox> wrapper = Wrappers.<InnerInbox>query()
//                .eq("is_read", GlobalConsts.NO_STR)
//                .eq("content_type", "news")
//                .eq("receiver_user_code", UserUtils.currentUser().getCode());
//        int count = service.count(wrapper);
        Integer count = service.countNews();
        return RestResult.ok("查询成功", count);
    }

    /**
     * 获取当前用户未读消息 最近的一条
     *
     * @return
     */
    @GetMapping("/msgUserTop1")
    public RestResult msgUserTop1(String currInnerNoticeId) {
        RestResult restResult= RestResult.ok("查询成功");
        if (StringUtils.isNotBlank(UtilCommon.getStr(currInnerNoticeId,null))) {
            service.update(Wrappers.<InnerInbox>update()
                    .set("is_read", GlobalConsts.YES_STR)
                    .set("gmt_read", new Date())
                    .eq("id", currInnerNoticeId)
            );
            restResult.setMsg("站内消息已自动已读");
        }

        this.insertNOtice();
        InnerInboxVO innerInboxVO =  service.msgUserTop1();
        if (innerInboxVO != null) innerInboxVO.setUnreadCount(service.countNews());
        restResult.setData(innerInboxVO);
        return restResult;
    }

    /**
     *   插入某些消息
     *
     * @return
     */
    public void insertNOtice() {

        //效期
        String sql= "select  TIMESTAMPDIFF(DAY,now(),ws.exp_date) due,ws.matr_name,ws.matr_spec,package_qty,exp_date,id,sn,rfid " +
                "from wm_stock ws " +
                "where package_qty != 0 and TIMESTAMPDIFF(DAY,now(),ws.exp_date) < 30   " +
                "order by TIMESTAMPDIFF(DAY,now(),ws.exp_date) asc LIMIT 1 ";
        Map<String, Object> map = null;
        try {
            map = jdbcTemplate.queryForMap(sql);
        }catch (Exception e){
        }
        if (map != null) {
            //推送消息给运营管理员
            String content = "品规："+map.get("matr_name")+"<br>";
            content+="效期："+map.get("exp_date")+"，剩余："+map.get("due")+"天<br>";
            content+="SN："+UtilCommon.getStr((String)map.get("sn"), "无")+"，RFID："+UtilCommon.getStr((String)map.get("rfid"), "无");
            CommonService.pushMessageRole("效期过期提醒:"+map.get("matr_name"),content, "admin,admin_yy", map.get("id")+"");
        }
    }

    /**
     * 获取当前用户未读消息 最近的一条
     *
     * @return
     */
    @GetMapping("/msgByNoticeId")
    public RestResult msgByNoticeId(String noticeId) {
        InnerInboxVO innerInboxVO  = service.getMsgByNoticeId(noticeId);
        if (innerInboxVO != null) {
            innerInboxVO.setUnreadCount(service.countNews());
        }
        return RestResult.ok("查询成功", innerInboxVO);
    }
}
